package com.nulldev.util.uri.yt.comments;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nulldev.util.lang.json.Json;
import com.nulldev.util.lang.json.JsonObject;
import com.nulldev.util.string.StringsUtil;

public class CommentMeta {
	
	public static final Pattern COMMENTS_PATTERN = Pattern.compile("(?<=\\'COMMENTS_TOKEN\\'\\: \\\")(.*)(?=\\\"\\,      \\'GET)");
	public static final Pattern XSRF_ID_PATTERN = Pattern.compile("(?<=XSRF_TOKEN\\'\\: \\\")(.*)(?=\\\"\\,      \\'XSRF_FIELD)");

	private final String pageData;
	private final JsonObject pageJson;
	
	public CommentMeta(final String pageData) {
		this.pageData = pageData;
		final String raw_json0 = "{\"" + 
    			StringsUtil.substringBetween(pageData, "var ytplayer = ytplayer || {};ytplayer.config = ", ";ytplayer.load = function() {");
    	final String raw_json = raw_json0.substring(2, raw_json0.length());
    			//StringsUtil.substringBetween(pageInfo, "var ytplayer = ytplayer || {};ytplayer.config = {\"", "};ytplayer.load = function() {") + "}";
    	this.pageJson = (raw_json.startsWith("<!DOCTYPE html>") ? Json.object() : Json.parseDEC(raw_json).asObject());
	}
	
	public String getToken() {
		final Matcher m = COMMENTS_PATTERN.matcher(pageData);
		m.find();
		return m.group();
	}
	
	public String getXSRF() {
		final Matcher m = XSRF_ID_PATTERN.matcher(pageData);
		m.find();
		return m.group();
		//return this.pageJson.get("args").asObject().getString("account_playback_token");
	}
	
	@Override
	public String toString() {
		return "Comments.Metadata[token=" + this.getToken() + ",xsrf=" + this.getXSRF() + ",itct=" + (this.getITCT() == null ? "null" : this.getITCT()) + "]";
	}

	public String getITCT() {
		try {
			return this.pageJson.get("args").asObject().getString("itct");
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
